// pages/outvisit/task/signIn.js
var api = require("../../../utils/api.js");
var util = require("../../../utils/util.js");
var amapFile = require("../../../libs/amap-wx.130.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,//任务ID
    busname: "",
    taskLongitude: "",//任务经度
    taskLatitude: "",//任务纬度
    taskAddress: "",//任务地址
    longitude: "",//地图当前经度
    latitude: "",//地图当前纬度
    withinNum: 3,//最大打卡范围公里数
    within: false,//是否在打卡范围以内
    locationName: "",//当前位置名称
    clockInDate: "",//打卡日期
    clockInTime: "",//打卡时间
    signInRecord: "",//最近签到记录
    street: "",
    township: "",
    remark: "",//备注
    amapWebServiceKey: "",
    amapKey: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id;

    var taskLongitude = options.taskLongitude;
    var taskLatitude = options.taskLatitude;
    var taskAddress = options.taskAddress;
    var busname = options.busname;

    //console.log("id=========>"+id);
    //console.log("taskLongitude=========>"+taskLongitude);
    //console.log("taskLatitude=========>"+taskLatitude);
    //console.log("taskAddress=========>"+taskAddress);

    api.getUsfulAmapInfo().then(res => {
      //console.log(res.data);
      var amapWebServiceKey = res.data.amapWebServiceKey;
      var amapKey = res.data.amapKey;

      // 设置坐标
      that.setData({
        amapWebServiceKey: amapWebServiceKey,
        amapKey: amapKey,
      }, () => {
      });

      var myAmapFun = new amapFile.AMapWX({
        key: that.data.amapKey
      });

      that.setData({
        id: id,
        markers: [],
        taskLongitude: taskLongitude,
        taskLatitude: taskLatitude,
        longitude: taskLongitude,
        latitude: taskLatitude,
        taskAddress: taskAddress,
        busname: busname,
      }, () => {
        // 处理空坐标问题
        that.setNullCoord(myAmapFun);
      });
    }).catch(() => {
      // 设置当前位置坐标
    });
  },

  showMarkerInfo: function(data,i){
    var that = this;
    that.setData({
      textData: {
        name: data[i].name,
        desc: data[i].address
      }
    });
  },

  changeMarkerColor: function(data,i){
    var that = this;
    var markers = [];
    for(var j = 0; j < data.length; j++){
      if(j==i){
        data[j].iconPath = "选中 marker 图标的相对路径"; //如：..­/..­/img/marker_checked.png
      }else{
        data[j].iconPath = "未选中 marker 图标的相对路径"; //如：..­/..­/img/marker.png
      }
      markers.push(data[j]);
    }
    that.setData({
      markers: markers
    });
  },

  getUsfulAmapInfo: function () {
    var that = this;
    api.getUsfulAmapInfo().then(res => {
      console.log(res.data);
      var amapWebServiceKey = res.data.amapWebServiceKey;
      var amapKey = res.data.amapKey;

      // 设置坐标
      that.setData({
        amapWebServiceKey: amapWebServiceKey,
        amapKey: amapKey,
      }, () => {
      });
    }).catch(() => {
      // 设置当前位置坐标
    });
  },

  // 处理空坐标问题
  setNullCoord: function (myAmapFun) {
    var that = this;
    var taskLongitude = that.data.taskLongitude;
    var taskLatitude = that.data.taskLatitude;
    if (taskLongitude === "undefined" || (!taskLongitude) || taskLongitude == 0 || taskLongitude == "") {
      //根据位置名称获取坐标
      api.getLocationByName(that.data.taskAddress,that.data.amapWebServiceKey).then(res => {
        console.log("res.result===================>");
        console.log(res.result);
        var longitude = res.result.location.lng;
        var latitude = res.result.location.lat;

        console.log("设置longitude====》"+longitude);
        console.log("设置latitude====》"+latitude);

        //var street = res.result.regeocodeData.street;
        //var township = res.result.regeocodeData.township;

        // 设置坐标
        that.setData({
          taskLongitude: longitude,
          taskLatitude: latitude,
          longitude: longitude,
          latitude: latitude,
          //street: street,
          //township: township,
        }, () => {
          // 设置当前位置坐标
          that.setLocation(myAmapFun);
        });
      }).catch(() => {
        // 设置当前位置坐标
        that.setLocation(myAmapFun);
      });
    } else {
      // 设置当前位置坐标
      that.setLocation(myAmapFun);
    }
  },

  // 定位到当前位置
  setLocation:function(myAmapFun){
    var that = this;
    var amapWebServiceKey = that.data.amapWebServiceKey;
    console.log("amapWebServiceKey==========>"+amapWebServiceKey);
    myAmapFun.getPoiAround({
      success: function(data){
        console.log(data);

        var markersData = data.markers;
        const longitude = markersData[0].longitude;
        const latitude = markersData[0].latitude;

        console.log("markersData=========>");
        console.log(markersData);
        //console.log(markersData[0]);
        //const street = markersData[0].regeocodeData.street;
        //const township = markersData[0].regeocodeData.township;

        if (longitude == 0 || latitude == 0) {
          return;
        }

        that.setData({
          longitude: longitude,
          latitude: latitude,
          //street: street,
          //township: township,
        }, () => {
          //获取当前位置名称
          that.getLocationName();
          //api.updateAmapTimes(amapWebServiceKey);
        });
      },
      fail: function(info){
        //失败回调
        // wx.showToast({
        //   title: "获取当前坐标失败",
        //   icon: "none"
        // });
      }
    })
  },

  // 标记点点击事件
  markerClick: function (res) {
    var that = this;
    //获得当前选中的任务数据
    var task = that.data.taskList[res.markerId];
    var curTaskId = task.outvisitId;
    var curIsReceived = task.isReceived;
    var curTaskLongitude = task.longitude;
    var curTaskLatitude = task.latitude;
    //console.log("经度：" + that.data.markers[res.markerId].longitude +"||纬度：" + that.data.markers[res.markerId].latitude);
    curTaskLongitude = parseFloat(that.data.markers[res.markerId].longitude);
    curTaskLatitude =  parseFloat(that.data.markers[res.markerId].latitude);
    var curTaskDistance = (parseInt(task.distance) / 1000).toFixed(2);
    var curTaskAddress = task.address;
    that.setData({
      curTaskId: curTaskId,
      curIsReceived: curIsReceived,
      curTaskLongitude: curTaskLongitude,
      curTaskLatitude: curTaskLatitude,
      curTaskDistance: curTaskDistance,
      curTaskAddress: curTaskAddress
    });
    that.taskInfoShowOrHide();
  },

  //获取当前位置名称
  getLocationName: function () {
    var that = this;
    //根据坐标获取位置名称
    api.getLocationName(that.data.longitude, that.data.latitude).then(res => {
      that.setData({
        locationName: res
      });
    });
  },

  // 设置打卡时间
  setClockInTime: function () {
    var myDate = Date.parse(new Date());
    var clockInDate = util.formatTimeTT(myDate, "Y年M月D日");
    var clockInTime = util.formatTimeTT(myDate, "h:m");
    this.setData({
      clockInDate: clockInDate,
      clockInTime: clockInTime
    });
  },

  // 获取今日出行打卡记录
  getClockInRecord: function () {
    var that = this;
    wx.showLoading();//显示加载中
    var f = false;
    api.getClockInRecord().then(res => {
      if (res.code == 0) {
        wx.hideLoading();
        var data = res.data;
        if (data && data.length != 0) {
          if (data[data.length - 1].clockType != 3) {
            f = true;
          }
        }

        if (f) {
          // 签到打卡
          api.checkin(that.data.id, that.data.longitude, that.data.latitude, that.data.locationName, that.data.remark);
        } else {
          wx.showToast({
            title: "请先开始行程",
            icon: "none"
          });
        }
      }
    });
  },

  // 签到按钮点击事件
  signInBtnClick: function () {
    //console.log("到这里了============》");
    var that = this;
    var busname = that.data.busname;
    //console.log("busname============》"+busname);

    wx.showModal({
      title: "提示",
      content: "签到成功",
      success: function (sm) {
        if (sm.confirm) {
          //console.log(that.data.locationName);

          async function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
          }

          async function timeout() {
            //先把坐标保存起
            let a21 = api.addSurveyLocationForApp(that.data.id, that.data.longitude, that.data.latitude, that.data.locationName,that.data.street,that.data.township).then(res => {
              var data = res;
            });

            //上传大坐标图片和小坐标图片到服务器上
            let a22 = await api.saveBigMapImage(that.data.id, that.data.longitude, that.data.latitude).then(res => {
              var data = res;
            });

            let a23 = await api.saveSmallMapImage(that.data.id, that.data.longitude, that.data.latitude).then(res => {
              var data = res;
            });

            await delay(1000);

            //公交站
            that.getUsfulAmapInfo();
            let a1 = await api.getRoundInfo2(that.data.longitude, that.data.latitude, '150700', that.data.amapWebServiceKey).then(res => {
              var data = res;

              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].address + ";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "858";
              if (busname == "住宅") {
                colid = "858";
              }
              else if (busname == "商业") {
                colid = "969";
              }
              else if (busname == "办公") {
                colid = "980";
              }

              api.addSurveyMapColumnValueForApp(that.data.id, colid, addressStr).then(res => {
                var data = res;

              });
            });

            await delay(1000);

            //地铁站
            that.getUsfulAmapInfo();
            let a2 = await api.getRoundInfo1(that.data.longitude, that.data.latitude, '150500', that.data.amapWebServiceKey).then(res => {
              var data = res;

              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].address + ";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              console.log(addressStr);

              var colid = "859";
              if (busname == "住宅") {
                colid = "859";
              }
              else if (busname == "商业") {
                colid = "970";
              }
              else if (busname == "办公") {
                colid = "981";
              }

              api.addSurveyMapColumnValueForApp(that.data.id, colid, addressStr).then(res => {
                var data = res;

              });
            });

            await delay(1000);
            //停车场
            that.getUsfulAmapInfo();
            let a3 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'150900', that.data.amapWebServiceKey).then(res => {
              var data = res;


              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "861";
              if (busname == "住宅") {
                colid = "861";
                api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                  var data = res;

                });
              }
              else if (busname == "商业") {
                colid = "861";
              }
              else if (busname == "办公") {
                colid = "861";
              }
            });
            await delay(1000);
            //交通地名
            that.getUsfulAmapInfo();
            let a4 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'190300', that.data.amapWebServiceKey).then(res => {
              var data = res;


              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "909";
              if (busname == "住宅") {
                colid = "909";
              }
              else if (busname == "商业") {
                colid = "961";
              }
              else if (busname == "办公") {
                colid = "979";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                var data = res;

              });
            });
            await delay(1000);
            //学校
            that.getUsfulAmapInfo();
            let a5 = await api.getRoundSchool(that.data.longitude,that.data.latitude,'141200', that.data.amapWebServiceKey).then(res => {
              var data = res;


              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "864";
              if (busname == "住宅") {
                colid = "864";
              }
              else if (busname == "商业") {
                colid = "972";
              }
              else if (busname == "办公") {
                colid = "982";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                var data = res;

              });
            });
            await delay(1000);
            //综合医院
            that.getUsfulAmapInfo();
            let a6 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'090100', that.data.amapWebServiceKey).then(res => {
              var data = res;


              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "865";
              if (busname == "住宅") {
                colid = "865";
              }
              else if (busname == "商业") {
                colid = "971";
              }
              else if (busname == "办公") {
                colid = "983";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                var data = res;
              });
            });
            await delay(1000);
            //休闲场所
            that.getUsfulAmapInfo();
            let a7 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'080500', that.data.amapWebServiceKey).then(res => {
              var data = res;


              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "866";
              if (busname == "住宅") {
                colid = "866";
                api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                  var data = res;

                });
              }
              else if (busname == "商业") {
                colid = "866";
              }
              else if (busname == "办公") {
                colid = "866";
              }

            });
            await delay(1000);
            //金融机构
            that.getUsfulAmapInfo();
            let a8 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'160100', that.data.amapWebServiceKey).then(res => {
              var data = res;
              //console.log("周边金融机构=======>");
              //console.log(data);

              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //(addressStr);

              var colid = "867";
              if (busname == "44") {
                colid = "867";
              }
              else if (busname == "45") {
                colid = "974";
              }
              else if (busname == "46") {
                colid = "985";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                var data = res;
              });
            });
            await delay(1000);
            //周边楼盘
            that.getUsfulAmapInfo();
            let a9 = await api.getRoundInfo1(that.data.longitude,that.data.latitude,'060200|060400', that.data.amapWebServiceKey).then(res => {
              var data = res;
              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var colid = "868";
              if (busname == "住宅") {
                colid = "868";
                api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                  var data = res;

                });
              }
              else if (busname == "商业") {
                colid = "868";
              }
              else if (busname == "办公") {
                colid = "868";
              }

            });
            await delay(1000);
            //周边商业
            that.getUsfulAmapInfo();
            let a10 = await api.getRoundBusinessInfo(that.data.longitude,that.data.latitude,'060200|060400', that.data.amapWebServiceKey).then(res => {
              var data = res;
              //console.log("商业====================>");
              //console.log(res);

              var addressStr = "";
              for (var poi in data.pois) {
                addressStr += data.pois[poi].name+";";
              }

              var addressArrAll = addressStr.split(";")
              addressArrAll = api.arrayUnique(addressArrAll);
              addressStr = addressArrAll.join(",");
              //console.log(addressStr);

              var lengthAddress = 0;
              if(addressArrAll.length > 1) {
                lengthAddress = "小于1公里";
              }
              else {
                lengthAddress = "大于1公里";
              }
              //console.log(lengthAddress);
              var colid = "920";
              if (busname == "住宅") {
                colid = "920";
              }
              else if (busname == "商业") {
                colid = "989";
              }
              else if (busname == "办公") {
                colid = "990";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,lengthAddress).then(res => {
                var data = res;
              });

              var colid = "866";
              if (busname == "住宅") {
                colid = "866";
              }
              else if (busname == "商业") {
                colid = "973";
              }
              else if (busname == "办公") {
                colid = "984";
              }
              api.addSurveyMapColumnValueForApp(that.data.id,colid,addressStr).then(res => {
                var data = res;
              });
            });
            await delay(500);
            let a11 = api.updateSurveyCoordinate(that.data.longitude,that.data.latitude,that.data.locationName).then(res => {
              if (res.code == 0) {
                wx.hideLoading();
                var data = res.data;

                api.surveyColumnComplete(that.data.id, "定位", that.data.userId).then(res => {
                  if (res.code == 0) {
                    wx.showToast({
                      title: '上传成功',
                      icon: 'none'
                    });

                  }
                }).catch(res => {
                  wx.hideLoading();
                  wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                  });
                });
              }
            });
          }

          timeout();

          let pages = getCurrentPages();//当前页面
          //console.log(pages);
          let prevPage = pages[pages.length - 2];//上一页面
          //console.log(prevPage);
          prevPage.getSurveyColumnComplete();
          // 返回
          wx.navigateBack({
            delta: 1,
          });
        }
      }
    })
  },

  beBackPage: function(e) {
    let pages = getCurrentPages();//当前页面
    //console.log(pages);
    let prevPage = pages[pages.length - 2];//上一页面
    //console.log(prevPage);
    prevPage.getSurveyColumnComplete();
    // 返回
    wx.navigateBack({
      delta: 1,
    });
  },

  // 输入框输入事件
  inputTyping: function (e) {
    this.setData({
      remark: e.detail.value.trim(),
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 设置打卡时间
    this.setClockInTime();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
